package com.dqlp.yf.rabbitmq.sender;

import com.dqlp.yf.rabbitmq.constant.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @program: rabbitmq
 * @description:
 * @author: andy
 * @create: 2019-09-08 23:08
 */
@Component
@Slf4j
public class TopicSender implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback{
    final
    RabbitTemplate rabbitTemplate;

    @Autowired
    public TopicSender(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setReturnCallback(this::returnedMessage);
        rabbitTemplate.setConfirmCallback(this::confirm);
        this.rabbitTemplate = rabbitTemplate;
    }

    public void sendTopic(String msg,String routingKey) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(MqConstant.TOPIC_EXCHANGE,routingKey,msg,correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info(correlationData+"&&&&&&&&&&&&&&&&&");
        log.info("队列收到信号");
        if (ack) {
            log.info("队列成功");
        } else {
            log.info("队列失败，出现异常");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
      //  System.out.println("7890");
        log.info(String.format("%s,%s,%s,%s",message,replyCode,replyText,exchange,routingKey));
    }
}
